import wepy from 'wepy'
import { platformCheckSession } from '../../utils/wx.login.utils.js'
import {
  couponActivityList,
  couponActivityJoinNum,
  couponsReceive,
  getIndexPageJson,
  getResidueNum,
  getPrize
} from '../../api'

export default class SpecialCoupon extends wepy.mixin {
  data = {
    groupActivity: {
      activityId: '',
      coupons: [],
      residueNum: 0
    },
    throttle: false
  }
  methods = {
    // 跳转套券详情
    navigationToSuitCouponFnc(e) {
      let { activityId } = e.currentTarget.dataset
      this.navigationToSuitCoupon(activityId)
    },
    // 领取卡券
    couponsReceive(e) {
      if (this.throttle) return
      const { parentIndex, index, info } = e.currentTarget.dataset
      const params = {
        channel: '5',
        activityId: info.activityId,
        tempNo: info.couponTplVo.tempNo
      }

      this.throttle = true
      wx.$request(couponsReceive, {
        data: params
      })
        .then(({ data }) => {
          this.pageModules[parentIndex].couponActivityElements[
            index
          ].joinNum += 1
          this.throttle = false
          this.$apply()
          const msg = '领取成功'
          wx.$tips.toast(msg)
        })
        .catch(({ data }) => {
          if (String(data.ecode) === '0050130008') {
            this.handleMemberRegister()
          } else {
            const msg = '领取失败'
            wx.$tips.toast(data.msg || msg)
          }
          this.throttle = false
          this.$apply()
        })
    },

    // 领取套券
    groupCouponReceiveFnc(e) {
      if (this.throttle) return
      let { activityId } = e.currentTarget.dataset
      this.groupCouponReceive(activityId)
    },
    // 关闭套券弹窗
    closegGroupCouponPopup() {
      this.groupActivity.residueNum = 0
    }
  }
  // 页面初始化后卡券相关逻辑处理
  couponsHandler() {
    let someDirectCoupon = this.pageModules.some(
      v => v.moduleType === 'DIRECT_COUPON'
    )
    let someGroupCoupon = this.pageModules.some(
      v =>
        v.moduleType === 'GROUP_COUPON' &&
        v.activityRuleConfig === 'AUTOMATE_DRAW'
    )

    // 需要授权的
    if (this.hasAuth) {
      someGroupCoupon && this.getGroupActivity('rceive')
      someDirectCoupon && this.getCouponActivity('joinNum')
    } else {
      platformCheckSession().then(data => {
        if (data && data.userId) {
          someGroupCoupon && this.getGroupActivity('rceive')
          someDirectCoupon && this.getCouponActivity('joinNum')
          this.hasAuth = true
          this.$apply()
        } else {
          // 未授权
          this.groupActivity.residueNum = 1
          this.$apply()
        }
      })
    }

    // 加载套券详情
    someGroupCoupon && this.getGroupActivity('detail')

    // 加载直接发券模块
    if (someDirectCoupon) {
      this.getCouponActivity('list')
      setTimeout(() => {
        wx.$tips.hideLoading()
      }, 500)
    } else {
      wx.$tips.hideLoading()
    }
  }

  // 跳转到套券详情
  navigationToSuitCoupon(activityId) {
    wx.$navigateTo({ url: `/pages/suit-coupon?activityId=${activityId}` })
  }

  // 获取套券详情/剩余领取次数
  getGroupActivity(type) {
    let pageModules = this.pageModules
    for (let i = 0; i < pageModules.length; i++) {
      let curr = pageModules[i]
      // 条件：商户后太勾选了弹窗
      if (
        curr.moduleType === 'GROUP_COUPON' &&
        curr.activityRuleConfig === 'AUTOMATE_DRAW'
      ) {
        let activityElement = curr.couponActivityElement
        let params = {
          activityId: activityElement.activityId
        }
        let url = type === 'detail' ? getIndexPageJson : getResidueNum
        wx.$request(url, { data: params }).then(
          ({ data }) => {
            if (type === 'detail') {
              // 套券详情
              // 条件: 还在有效期内
              let timestamp = Date.now()
              if (data.activityInfoVo.activeEnd > timestamp) {
                data.couponTpls.forEach((v, i) => {
                  if (v.discountRate)
                    v.discountRate = (v.discountRate * 10).toFixed(1)
                  if (v.denomination)
                    v.denomination = parseInt(v.denomination / 100, 10)
                  if (v.orderAmount)
                    v.orderAmount = parseInt(v.orderAmount / 100, 10)
                  // 卡券样式大小
                  if (data.couponTpls.length <= 3) {
                    v.class = 'long'
                  } else {
                    if (data.couponTpls.length % 2 === 0) v.class = 'short'
                    else v.class = i === 0 ? 'long' : 'short'
                  }
                })
                this.groupActivity.coupons = data.couponTpls
              }
            } else {
              // 剩余领取次数
              this.groupActivity.residueNum = data.residueNum
            }
            this.groupActivity.activityId = activityElement.activityId
            this.$apply()
          },
          data => {
            const msg = data.msg
            wx.$tips.toast(msg)
          }
        )
        break
      }
    }
  }

  // 获取直接发券卡券 列表/已领取次数
  getCouponActivity(type) {
    let pageModules = this.pageModules

    for (let i = 0; i < pageModules.length; i++) {
      let curr = pageModules[i]

      if (curr.moduleType === 'DIRECT_COUPON') {
        let activityElements = curr.couponActivityElements
        let url = type === 'list' ? couponActivityList : couponActivityJoinNum
        let params = {
          activityIdStr: activityElements.map(v => v.activityId).join(',')
        }
        if (type === 'list') params.thirdPartyId = this.getPageId()

        wx.$request(url, { data: params }).then(
          ({ data }) => {
            if (type === 'list') {
              // 列表
              data.forEach(v => {
                if (v.couponTplVo.activeBegin) {
                  v.couponTplVo.activeBegin = v.couponTplVo.activeBegin.replace(
                    /-/g,
                    '.'
                  )
                  v.couponTplVo.activeEnd = v.couponTplVo.activeEnd.replace(
                    /-/g,
                    '.'
                  )
                }

                if (v.couponTplVo.discountRate)
                  v.couponTplVo.discountRate = (
                    v.couponTplVo.discountRate * 10
                  ).toFixed(1)
                if (v.couponTplVo.denomination)
                  v.couponTplVo.denomination = parseInt(
                    v.couponTplVo.denomination / 100,
                    10
                  )
                if (v.couponTplVo.orderAmount)
                  v.couponTplVo.orderAmount = parseInt(
                    v.couponTplVo.orderAmount / 100,
                    10
                  )

                activityElements.forEach((element, ei) => {
                  if (element.activityId === v.activityId)
                    activityElements[ei].info = v
                })
              })
              // 删除activityElements里面没有匹配的项目
              // 接口只查询有效期内的卡券
              this.pageModules[
                i
              ].couponActivityElements = activityElements.filter(
                v1 => !!v1.info
              )
            } else {
              // 领取次数
              data.forEach(v => {
                activityElements.forEach((element, ei) => {
                  if (element.activityId === v.activityId) {
                    activityElements[ei].joinNum = v.joinNum
                  }
                })
              })
            }
            this.$apply()
          },
          data => {
            const msg = data.msg
            wx.$tips.toast(msg)
          }
        )
      }
    }
  }

  // 领取套券
  groupCouponReceive(activityId) {
    if (this.throttle) return
    let params = { activityId }
    this.throttle = true

    wx.$request(getPrize, {
      data: params
    })
      .then(({ data }) => {
        this.groupActivity.residueNum = 0
        this.throttle = false
        this.$apply()
        const msg = '领取成功'
        wx.$tips.toast(msg)
      })
      .catch(({ data }) => {
        this.throttle = false
        this.$apply()
        const msg = data.ecode === '0030010010' ? '你已经领取过了' : data.msg
        wx.$tips.toast(msg)
      })
  }
}
